import { createStore } from 'vuex'
import httpRequest from '@/service'
import { setToken } from '@/utils/auth'
import { ElMessage } from 'element-plus'
import { setStartDate } from '@/utils/auth'

interface IData {
  userInfo: string
  timestamp: string
}

export default createStore({
  state: {
    scroll: false,
    globalDate: {
      startDate: '', // 开始日期
      endDate: '' // 结束日期
    }
  },
  mutations: {
    changeDate(state: any, data: any) {
      if (data) {
        state.globalDate.startDate = data.startDate
        state.globalDate.endDate = data.endDate
        setStartDate(data.startDate)
      }
    },
    setScroll: (state, newScroll) => {
      state.scroll = newScroll
    }
  },
  actions: {
    async getToken(state: any, data: IData) {
      return new Promise((resolve, reject) => {
        httpRequest
          .post({
            url: 'zdcommon/SSO/sm2SsoLogin',
            data: data
          })
          .then((res: any) => {
            if (res.code == 200) {
              setToken(res.data.token)
              resolve(res)
            } else {
              ElMessage.warning({
                message: res.message || '获取用户信息失败'
              })
              setTimeout(() => {
                reject(res)
              }, 1000)
            }
          })
          .catch((err) => {
            ElMessage.warning({
              message: err.message || '获取用户信息失败'
            })
            setTimeout(() => {
              reject(err)
            }, 1000)
          })
      })
    }
  },
  modules: {}
})
